//
//  PersonalViewController.m
//  PaiLeXiongProject
//
//  Created by 小獾科技 on 2017/9/8.
//  Copyright © 2017年 小獾科技. All rights reserved.
//

#import "PersonalViewController.h"
#import "MinePersonalHeadCell.h"
#import "PersonalListTableViewCell.h"
#import "PhoneBindViewController.h"
#import "TPKeyboardAvoidingScrollView.h"
@interface PersonalViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *btn;
@property (nonatomic, strong) UIButton *button;
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, copy) NSString *dataString;
@property (nonatomic, copy) NSString *phonoNumber;
@property (nonatomic, copy) NSString *userName;
@property (nonatomic, copy) NSString *babyName;
@property (nonatomic, copy) NSString *sex;
@property (nonatomic, copy) NSString *birthday;
@property (nonatomic, strong) ImageActionSheet *imageActionSheet;
@property (nonatomic, copy) NSString *imageUrl;
@property (nonatomic, strong) TPKeyboardAvoidingScrollView *backgroundView;
@end


@implementation PersonalViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _imageUrl = USER_HEAD;
    [self addBackItem];
    self.title = @"编辑个人资料";
    
    _backgroundView = [[TPKeyboardAvoidingScrollView alloc] initWithFrame:CGRectMake(0, 0, GWIDTH, GHEIGHT - 64)];
    [self.view addSubview:_backgroundView];
    
    _dataString = BABY_BIRTHDAY;
    [self addRightBarButtonWithTitle:@"保存" andSel:@selector(handleSavaBtn)];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, GWIDTH, GHEIGHT) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorColor = ColorClear;
    _tableView.tableFooterView = [UIView new];
    [_tableView registerClass:[MinePersonalHeadCell class] forCellReuseIdentifier:@"head"];
    [_tableView registerClass:[PersonalListTableViewCell class] forCellReuseIdentifier:@"list"];
    [_backgroundView addSubview:_tableView];
    [self createDatePickView];
}

//保存按钮响应方法
- (void)handleSavaBtn
{
    [self.view endEditing:YES];
    
    UITextField *name = [self.view viewWithTag:111];//姓名
    UITextField *babyName = [self.view viewWithTag:112];
    
    NSDictionary *param = @{@"avatar"       : _imageUrl,
                            @"username"     : name.text,
                            @"babyName"     : babyName.text,
                            @"babySex"      : _sex,
                            @"babyBirthday" : _birthday
                                };
    [NetWork sendPostRequestURL:[NSString stringWithFormat:@"%@/common/SetUserINFO", GW_Domain] parameters:param completionBlockWithSuccess:^(NSDictionary *resultDict) {
//        NSLog(@"%@", resultDict);
        NSDictionary *dict = resultDict[@"data"];
        if (dict && [dict isKindOfClass:[NSDictionary class]]) {
            [GW_Tool saveLoginInfoWithDict:dict];// 保存用户信息
            MESSAGE_TOAST(resultDict[@"message"]);
        }
        [self.navigationController popViewControllerAnimated:YES];
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"%@", error);
        MESSAGE_TOAST(@"出错了");
    }];
}

- (void)createDatePickView
{
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, GWIDTH, GHEIGHT)];
    _bgView.backgroundColor = ColorFrom16A(0x000000, 0.8);
    _bgView.hidden = YES;
    [self.navigationController.view addSubview:_bgView];
    
    UIView *view = [UIView new];
    view.backgroundColor = ColorWhite;
    [_bgView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_bgView);
        make.left.and.right.equalTo(_bgView);
        make.height.equalTo(@235);
    }];
    
    UILabel *label = [UILabel new];
    label.text = @"选择宝宝生日";
    label.textColor = ColorFrom16(0xF6D04A);
    label.font = PFRFONT(14);
    [view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view).offset(29);
        make.centerX.equalTo(view.mas_centerX);
        make.width.equalTo(@88);
        make.height.equalTo(@20);
    }];
    
    UIDatePicker *datePicker = [UIDatePicker new];
    //设置显示方式  这里只显示年月日
    datePicker.datePickerMode = UIDatePickerModeDate;
    datePicker.height = 38;
    datePicker.backgroundColor = ColorWhite;
    datePicker.maximumDate = [NSDate date];
    [datePicker addTarget:self action:@selector(datePickerValueChanged:)forControlEvents:UIControlEventValueChanged];
    //设置本地化支持的语言（在此是中文)
    datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
    [view addSubview:datePicker];
    [datePicker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(label.mas_bottom).offset(34);
        make.left.equalTo(_bgView);
        make.right.equalTo(_bgView);
        make.height.equalTo(@114);
    }];
    
    
    UIView *topView = [UIView new];
    topView.backgroundColor = ColorFrom16(0xFEDE6D);
    [_bgView addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(view.mas_top);
        make.left.and.right.equalTo(_bgView);
        make.height.equalTo(@44);
    }];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setTitle:@"取消" forState:0];
    [cancelBtn setTitleColor:ColorFrom16(0x323232) forState:0];
    cancelBtn.titleLabel.font = PFRFONT(16);
    [cancelBtn addTarget:self action:@selector(handleCancleBtn) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(topView.mas_centerY);
        make.left.equalTo(topView).offset(52);
        make.width.equalTo(@32);
        make.height.equalTo(@22);
    }];
    
    UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [sureBtn setTitle:@"确定" forState:0];
    [sureBtn addTarget:self action:@selector(handleSureBtn) forControlEvents:UIControlEventTouchUpInside];
    [sureBtn setTitleColor:ColorFrom16(0x323232) forState:0];
    sureBtn.titleLabel.font = PFRFONT(16);
    [topView addSubview:sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(topView.mas_centerY);
        make.right.equalTo(topView).offset(-52);
        make.width.equalTo(@32);
        make.height.equalTo(@22);
    }];
}

- (void)datePickerValueChanged:(UIDatePicker *)sender
{
    NSDate *date = sender.date;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    _dataString = [dateFormatter stringFromDate:date];
}

//取消
- (void)handleCancleBtn
{
    [UIView animateWithDuration:1.0 animations:^{
        _bgView.hidden = YES;
    }];
}
//确定
- (void)handleSureBtn
{
    [UIView animateWithDuration:1.0 animations:^{
        _bgView.hidden = YES;
    }];
    [_tableView reloadData];
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
        return 80;
    else
        return 60;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
    {
        MinePersonalHeadCell *cell = [tableView dequeueReusableCellWithIdentifier:@"head"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        [cell.headImg sd_setImageWithURL:[NSURL URLWithString:_imageUrl] placeholderImage:IMAGE(@"header_default")];
        cell.leftImg.image = IMAGE(@"person_img");
        NSLog(@"头像 %@", _imageUrl);
        return cell;
    }
    else
    {
        PersonalListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"list"];
      
        switch (indexPath.row) {
            case 1:
                cell.leftImg.image = IMAGE(@"person_userName");
                if(cell.textfield.text.length > 0)
                {
                    _userName = cell.textfield.text;
                }
                else
                {
                    _userName = USER_NAME;
                }
                cell.textfield.tag = 111;
                cell.label.text = @"昵称";
                cell.textfield.hidden = NO;
                cell.textfield.text = _userName;
                cell.textfield.placeholder = @"请填写";
                [cell.textfield setValue:ColorFrom16A(0xEDC330, 1) forKeyPath:@"_placeholderLabel.textColor"];//通过kvc去改变占位符的字体颜色
                [cell.textfield setValue:PFRFONT(14) forKeyPath:@"_placeholderLabel.font"];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
            case 2:
                cell.leftImg.image = IMAGE(@"person_phoneNum");
                cell.label.text = @"手机号";
                cell.textfield.hidden = NO;
                
                if([_phonoNumber isPhoneNumber])
                    cell.textfield.text = _phonoNumber;
                else
                    cell.textfield.text = USER_TEL;
                
                cell.textfield.userInteractionEnabled = NO;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
            case 3:
                cell.leftImg.image = IMAGE(@"person_babyName");
                if(cell.textfield.text.length > 0)
                {
                    _babyName = cell.textfield.text;
                }
                else
                {
                    _babyName = BABYNAME;
                }
                cell.textfield.tag = 112;
                cell.label.text = @"宝宝姓名";
                cell.textfield.hidden = NO;
                cell.textfield.text = _babyName;
                cell.textfield.placeholder = @"请填写";
                [cell.textfield setValue:ColorFrom16A(0xEDC330, 1) forKeyPath:@"_placeholderLabel.textColor"];//通过kvc去改变占位符的字体颜色
                [cell.textfield setValue:PFRFONT(14) forKeyPath:@"_placeholderLabel.font"];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
            case 4:
                cell.leftImg.image = IMAGE(@"person_babySex");
                cell.label.text = @"宝宝性别";
                cell.maleBtn.hidden = NO;
                cell.famaleBtn.hidden = NO;
                [cell.maleBtn addTarget:self action:@selector(handleMaleBtn:) forControlEvents:UIControlEventTouchUpInside];
                _btn = cell.maleBtn;
                _button = cell.famaleBtn;
                [cell.famaleBtn addTarget:self action:@selector(handleFamaleBtn:) forControlEvents:UIControlEventTouchUpInside];
                if([BABYSEX isEqualToString:@"1"])
                {
                    cell.maleBtn.backgroundColor = ColorFrom16(0xFEDE6D);
                    cell.famaleBtn.backgroundColor = ColorFrom16(0xF7F7F7);
                }
                else
                {
                    cell.maleBtn.backgroundColor = ColorFrom16(0xF7F7F7);
                    cell.famaleBtn.backgroundColor = ColorFrom16(0xFEDE6D);
                }
                if(cell.maleBtn.selected == YES)
                {
                    _sex = @"1";
                }
                else
                {
                    _sex = @"2";
                }
                break;
            case 5:
                cell.leftImg.image = IMAGE(@"person_babyBirthday");
                cell.label.text = @"宝宝出生日期";
                cell.textfield.hidden = NO;
                cell.textfield.userInteractionEnabled = NO;
                if(_dataString.length>0)
                {
                    cell.textfield.text = _dataString;
                }
                else
                {
                    cell.textfield.placeholder = @"未选择";
                }
                
                _birthday = cell.textfield.text;

                [cell.textfield setValue:ColorFrom16A(0xEDC330, 1) forKeyPath:@"_placeholderLabel.textColor"];//通过kvc去改变占位符的字体颜色
                [cell.textfield setValue:PFRFONT(14) forKeyPath:@"_placeholderLabel.font"];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                break;
                
            default:
                break;
        }
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.view endEditing:YES];
    if(indexPath.row == 0)
    {
        [self changeHeadImage];
    }
    if(indexPath.row == 2)
    {
        PhoneBindViewController *phone = [PhoneBindViewController new];
        phone.string = @"个人信息";
        phone.telephoneNumBlock = ^(NSString *string) {
            _phonoNumber = string;
        };
        [self.navigationController pushViewController:phone animated:YES];
    }
    if(indexPath.row == 5)
    {
        [UIView animateWithDuration:1.0 animations:^{
            _bgView.hidden = NO;
        }];
    }
}

- (void)changeHeadImage
{
    if (_imageActionSheet) {
        _imageActionSheet = nil;
    }
    @weakobj(self);
    _imageActionSheet = [[ImageActionSheet alloc] initInVC:self isUserPortrait:YES];
    _imageActionSheet.resultBlock = ^(UIImage *image, NSString *imageBase64) {
        
        @strongobj(self);
        if (image) {
            [self uploadImage:image];
        }
    };
    [_imageActionSheet showInView:self.view];
}

//上传头像
- (void)uploadImage:(UIImage *)image {
    
    // image是原图片，imageBase64是base64编码
    // 下面调上传头像接口
    [SVProgressHUD show];
    @weakobj(self);
    NSArray *array = @[image];
    [NetWork uploadImageRequestURL:[NSString stringWithFormat:@"%@/image/Upload",GW_Domain] imageArray:array parameters:nil progress:^(float progress) {
        [SVProgressHUD showProgress:progress];
        
    } completionBlockWithSuccess:^(NSDictionary *resultDict) {
        
        @strongobj(self);
        MESSAGE_TOAST(@"上传成功");
//        NSLog(@"%@", resultDict);
        NSArray *array = resultDict[@"data"];
        NSDictionary *dict = array[0];
        self.imageUrl = dict[@"uri"];
        [[NSUserDefaults standardUserDefaults] setObject:self.imageUrl forKey:@"imageurl"];
        if (self.imageUrl.length > 0) {
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        }
    } andFailure:^(NSError *error, NSString *errorMsg) {
        MESSAGE_TOAST(errorMsg);
    }];
}

- (void)handleMaleBtn:(UIButton *)sender
{
    sender.selected = YES;
    sender.backgroundColor = ColorFrom16(0xFEDE6D);
    _button.backgroundColor = ColorFrom16(0xF7F7F7);
    _button.selected = NO;
    _sex = @"1";
}

- (void)handleFamaleBtn:(UIButton *)sender
{
    sender.selected = YES;
    _btn.selected = NO;
    sender.backgroundColor = ColorFrom16(0xFEDE6D);
    _btn.backgroundColor = ColorFrom16(0xF7F7F7);
    _sex = @"2";
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    
//    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [_tableView reloadData];
    self.navigationController.navigationBar.barTintColor = ColorFrom16(0xFEDE6D);

}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
//    [self.navigationController setNavigationBarHidden:NO animated:animated];
    self.navigationController.navigationBar.barTintColor = ColorWhite;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
